package com.hotagent.jmx;

import com.hotagent.LogUtil;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

public class JmxClient {
    private static Object invoke(MBeanServerConnection connection, String bean, String method, Object[] params, String[] signature) throws Exception {
        ObjectName mbeanName = new ObjectName(bean);
        return connection.invoke(mbeanName, method, params, signature);
    }

    public static void main(String[] args) throws Exception {
        if (args.length < 2) {
            LogUtil.hotAgent.info("java -jar JmxClient ip port [params]");
            System.exit(0);
        }

        String ip = args[0];
        String port = args[1];

        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + ip + ":" + port + "/jmxrmi");
        JMXConnector connector = JMXConnectorFactory.connect(url, null);
        MBeanServerConnection connection = connector.getMBeanServerConnection();

        Object result = reload(connection);
        LogUtil.hotAgent.info(result.toString());
        LogUtil.hotAgent.info("jmx success");
    }

    private static Object reload(MBeanServerConnection connection) throws Exception {
        return invoke(connection, "HotAgent:type=Reload", "reload", new Object[]{}, new String[]{});
    }

}
